<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
 * 用户模块
 * 此模块基本模仿CI方法 参与于方法名一致
 *
 */
class User_model extends MY_Model{
	const DB = 'user';
	const MY_USER_CHECK_USERNAME_FAILED = -1;
	const MY_USER_USERNAME_BADWORD = -2;
	const MY_USER_USERNAME_EXISTS = -3;
	const MY_USER_EMAIL_FORMAT_ILLEGAL = -4;
	const MY_USER_EMAIL_ACCESS_ILLEGAL = -5;
	const MY_USER_EMAIL_EXISTS = -6;
	const MY_USER_EDIT_NULL = -7;
	const MY_USER_EDIT_ERROR = -8;
	const MY_USER_QUESTIONID_ERROR = -9;
	const MY_USER_ANSWER_ERROR = -10;
	public function __construct()
	{
		parent::__construct();	
	}
	
	/*
	 *用户登录
	 *@string username 	用户名 / 用户 ID / 用户 E-mail
	 *@string password 	密码
	 *@bool isuid 	是否使用用户 ID登录 1:使用用户 ID登录  2:使用用户 E-mail登录  0:(默认值) 使用用户名登录
	 *@bool checkques 	是否验证安装提问 1:验证安全提问 0:(默认值) 不验证安全提问
	 *@integer questionid 	安全提问索引
	 *@string answer 	安全提问答案
	 *--------------返回值--------------
	 *@array 	integer [0] 	大于 0:返回用户 ID，表示用户登录成功
	 *@-1:用户不存在，或者被删除
	 *@-2:密码错
	 *@-3:安全提问错
	 *@string [1] 	用户名
	 *@string [2] 	密码
	 *@string [3] 	Email
	 *@bool [4] 	用户名是否重名
	 *
	 *------------------------------------------
	 */	
	public function user_login($username, $password, $isuid = 0, $checkques = 0, $questionid = '', $answer = '')
	{
		$login_type = 'email';
		switch($isuid)
		{
			case 0:
				$login_type = 'username';
			break;
			case 1:
				$login_type = 'uid';
			break;
		}
		$this->db->where($login_type, $username);
		$this->db->select('uid,username,password,email,questionid,answer');
		$this->db->from(self::DB);
		$query = $this->db->get();
		$query = $query->result();
		if(isset($query[0]->username))
		{
			$userdata = array('uid'=>$query[0]->uid,'username'=>$query[0]->username,'password'=>$query[0]->password,'email'=>$query[0]->email,'questionid'=>$query[0]->questionid,'answer'=>$query[0]->answer);
			
		}
		else
		{
			return self::MY_USER_CHECK_USERNAME_FAILED;
		}
		
		if($this->password($password) != $userdata['password'])
		{
			return self::MY_USER_USERNAME_BADWORD;
		}
		if($checkques != 0  && ($questionid != $userdata['questionid'] || $answer != $userdata['answer']))
		{
			return self::MY_USER_USERNAME_EXISTS;
		}
		return array('uid'=>$userdata['uid'],'email'=>$userdata['email'],'username'=>$userdata['username'],1=>$userdata['username'],2=>$userdata['password'],3=>$userdata['email'],4=>false);

	}
	
	/*
	 *用户注册
	 *@param string username 	用户名
	 *@param string password 	密码
	 *@param string email 	电子邮件
	 *@param integer questionid 	安全提问索引
	 *@param string answer 	安全提问答案
	 *@return bool
	 *----------返回值--------------
	 *大于 0:返回用户 ID，表示用户注册成功
	 *-1:用户名不合法
	 *-2:包含不允许注册的词语
	 *-3:用户名已经存在
	 *-4:Email 格式有误
	 *-5:Email 不允许注册
	 *-6:该 Email 已经被注册
	 *--------------------------------------
	 */	
	public function user_register($username, $password, $email = false, $questionid = '', $answer = '', $regip = '',$ucid='')
	{
		if(!check_username($username))
		{
			return self::MY_USER_CHECK_USERNAME_FAILED;
		}
		if($this->get_user($username) !== false)
		{
			return self::MY_USER_USERNAME_EXISTS;
		}
		if($email !== false)
		{
			$email_tnf = check_emailformat($email);
			if($email_tnf != 1)
			{
				return $email_tnf;
			}
		}
		$data = array(
			'uid' => $ucid,
			'username' => $username ,
			'password' => $this->password($password) ,
			'time' => time(),
			'email' => $email,
			'questionid' => $questionid,
			'answer' => $answer,
			'regip' => $regip
        );
		$this->db->insert(self::DB, $data); 
		return $this->db->insert_id();
	}


	/*
	 *更新本地用户表资料
	 *@string username 	用户名
	 *@string oldpw 	旧密码
	 *@string newpw 	新密码，如不修改为空
	 *@string email 	Email，如不修改为空
	 *@bool ignoreoldpw 是否忽略旧密码  1:忽略，更改资料不需要验证密码  0:(默认值) 不忽略，更改资料需要验证密码
	 *@integer questionid 	安全提问索引
	 *@string answer 	安全提问答案
	 *@bool spcord 安全引索 是否需要验证 true：需要  false：不需要
	 *return integer
	 *----------返回值--------------
	 *1:更新成功
	 *0:没有做任何修改
	 *-1:旧密码不正确
	 *-2:用户不存在
	 *-4:Email 格式有误
	 *-6:该 Email 已经被注册
	 *-7:没有做任何修改
	 *-8:该用户受保护无权限更改
	 *-9:安全引索提问错误
	 *-10:
         * 安全引索回答错误
	 *--------------------------------------
	 */
	public function user_edit($username, $oldpw, $newpw, $email = '', $ignoreoldpw = 0, $questionid = '', $answer = '',$spcord = true)
	{
		if($email != '' && !check_emailformat($email))
		{
			return self::MY_USER_EMAIL_FORMAT_ILLEGAL;
		}
		/*
		 * 获取用户信息 
		 * 如果 ignoreoldpw 为0的话 就取消密码的判断
		 */
		if(0 == $ignoreoldpw)
		{
			$userdata =  $this->get_user($username);
		}
		else
		{
			$userdata =  $this->get_user($username,$oldpw);
		}
		if($userdata === false) //判断用户是否存在
		{
			return self::MY_USER_USERNAME_BADWORD;
		}
		else
		{
			if($newpw == $userdata['password'] and ($email != '' || $userdata['email'] == $userdata['email']))
			{
				return 0;
			}
			if($email != '' and self::MY_USER_EMAIL_EXISTS == $this->user_checkemail($email))//判断email是否被注册
			{
				return self::MY_USER_EMAIL_EXISTS;
			}
			$data = array();
			if(0 == $ignoreoldpw && $userdata['password'] != $oldpw) //判断修改密码 是否需要旧密码  如果需要:判断旧密码是否正确
			{
				return self::MY_USER_CHECK_USERNAME_FAILED;
			}
			if($spcord) //验证安全引索
			{
				if($userdata['questionid'] != $questionid)
				{
					return self::MY_USER_QUESTIONID_ERROR;
				}
					if($userdata['answer'] != $answer)
				{
					return self::MY_USER_ANSWER_ERROR;
				}
			}
			$this->db->where('username',$username);
			if($email != '')
			{
				$data['email'] = $email;
			}
			$data['password'] = $this->password($newpw);
			$this->db->update(self::DB, $data);
                        $this->db->last_query();
			return 1;
		}
	}

	/*
	 *判断本地用户是否存在
	 *@param string username 用户名
	 *@param string password 密码
	 *@bool isuid 	是否使用用户 ID获取	1:使用用户 ID获取	0:(默认值) 使用用户名获取
	 *@return bool
	 */
	public function get_user($username,$password = false,$isuid = 0,$return_data = array('uid'=>'uid','username'=>'username','password'=>'password','email'=>'email','questionid'=>'questionid','answer'=>'answer'))
	{
		$select_where = ($isuid == 0)?'username':'uid';
		$this->db->where($select_where, $username);
		if($password !== false)
		{
			$this->db->where('password', $this->password($password));
		}
		$this->db->select('uid,username,password,email,questionid,answer');
		$this->db->from(self::DB);
		$query = $this->db->get();
		$query = $query->result();
		if(isset($query[0]->username))
		{
			$return = array();
			foreach($return_data as $id=>$item)
			{
				$return[$id] = isset($query[0]->$item)?$query[0]->$item:false;
			}
		}
			return isset($return)?$return:false;
	}

	/*
	 *检查 Email 地址
	 *@string email 	Email
	 *@return  integer
	 *----------返回值--------------
	 * 1:成功
	 * -4:Email 格式有误
	 * -5:Email 不允许注册
	 * -6:该 Email 已经被注册
	 *--------------------------------------
	 */
	public function user_checkemail($email)
	{
		if(!check_emailformat($email))
		{
			return self::MY_USER_EMAIL_FORMAT_ILLEGAL;
		}
		$this->db->where('email', $email);
		$this->db->from(self::DB);
		$query = $this->db->count_all_results();
		if($query > 0)
		{
			return self::MY_USER_EMAIL_EXISTS;
		}
			return 1;
	}
	/*
	 *删除用户
	 *@integer/array uid 	用户名
	 *return integer
	 *----------ucenter 返回值--------------
	 *1:成功
	 *0:失败
	 *--------------------------------------
	 */
	public function user_delete($uid)
	{
		if(is_array($uid))
		{
			foreach($uid as $item)
			{
				if(is_numeric($item))
				{
					$this->db->where($type,$item);
				}
				else
				{
					return 0;
				}
			}
		}
		else
		{
			$this->db->where('uid',$uid);
		}
		$this->db->delete(self::DB);
		return 1;
	}
	
	/*
	 *检查用户名
	 *@string username 	用户名
	 *@return  integer
	 *----------ucenter 返回值--------------
	 * 1:成功
	 * -1:用户名不合法
	 * -2:包含要允许注册的词语
	 * -3:用户名已经存在
	 *--------------------------------------
	 */
	public function user_checkname($username)
	{
		if(!check_username($username))
		{
			return self::MY_USER_CHECK_USERNAME_FAILED;
		}
		if($this->get_user($username) !== false)
		{
			return self::MY_USER_USERNAME_EXISTS;
		}
		return 1;
	}


	/*
	 *退出登录
	 *return bool
	 */
	public function outlogin()
	{
		$this->session->sess_destroy();
		set_cookie('token',$token,time()-3600,base_url());
		return true;		
	}	
	
	/*
	*-----------------------------
	*以邮件找回密码
	*@param string user 用户名
	*@param string newpass 密码
	*@param string emailtitle 邮件标题
	*@param string emaildata 邮件内容
	*return true 修改成功 false 邮件发送失败 -1没有这个用户  -2 修改失败 -3 邮箱不正确
	*----------- ------------------
	*/
	public function edit_pass($user,$newpass,$email,$emailtitle,$emaildata)
	{
		$userdata = $this->get_user($user);
		if($userdata == 0)
		{
			return self::MY_USER_CHECK_USERNAME_FAILED;
		}
		if($email != $userdata[2])
		{
			return self::MY_USER_USERNAME_EXISTS;
		}
		$ts = $emaildata.$newpass;
		$this->load->library('email');
		$this->email->getTo($userdata[2]);
		$this->email->getSubject($emailtitle);
		$this->email->getBody($emaildata.$newpass);
		$email = $this->email->main();
		if($email == false)
		{
			return false;
		}
		else
		{
			if($this->myuc->uc_user_edit($user,'',$newpass,'',1) === 1)
			{
				return true;
			}
			else
			{
				return self::MY_USER_USERNAME_BADWORD;
			}

		}
	}
	
	/*
	 *密码加密函数  对密码进行加密
	 *@param string password 密码
	 *return string
	 *@Author seven
	 *@email 397109515@qq.com
	 */
	public function password($password)
	{
		return md5(md5($password.md5('seven')));
	}
	/*
	 * 根据email获得用户名
	 * @param string email 用户的email
	 * return string 用户名   -1 没有这个用户
	 */
	public function email_get_user($email)
	{
		$this->db->where('email', $email);
		$this->db->select('username');
		$this->db->from(self::DB);
		$query = $this->db->get();
		$query = $query->result();
		if(isset($query[0]->username))
		{
			return $query[0]->username;
		}
		else
		{
			return -1;
		}
	}
}